package com.Test;

import com.itheima.pojo.Employee;
import com.itheima.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class EmployeeTest {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    @Before
    public void init(){
        //定义读取文件名
        String resource = "mybatis-config.xml";
        //创建流
        Reader reader = null;
        try{
            //读取mybatis-config.xml文件到reader对象中
            reader = Resources.getResourceAsReader(resource);
            //初始化mybatis,创建SqlSessionFactory类的对象
            SqlSessionFactory sqlMapper = new
                    SqlSessionFactoryBuilder().build(reader);
            //创建SqlSession对象
            sqlSession = sqlMapper.openSession();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    @Test
    public void selectByPrimaryTest(){
        Long employeeId = 1L;
        //SqlSession执行映射文件中定义的SQL，并返回映射结果
        List<Employee> list = sqlSession.selectList("com.itheima.mapper.EmployeeMapper.selectByPrimaryKey",employeeId);
        for (Employee employee : list) {
            System.out.println(employee);
        }
    }
    @Test
    public void deleteByPrimaryKeyTest(){
            // 假设要删除的员工ID为1
            Long employeeId = 4L;
            // 执行删除操作
            int rowsAffected = sqlSession.delete("com.itheima.mapper.EmployeeMapper.deleteByPrimaryKey", employeeId);
            // 验证删除结果
            assertEquals(1, rowsAffected); // 假设成功删除一条记录应该返回1
    }
    @Test
    public void insertTest(){
        //SqlSession执行映射文件中定义的SQL，并返回映射结果
        Employee employee = new Employee();
        employee.setSid(4);
        employee.setSname("张三");
        employee.setSage(20);
        employee.setSposition("员工");
        List<Employee> list = sqlSession.selectList("com.itheima.mapper.EmployeeMapper.insert",employee);
        for (Employee employee1 : list) {
            System.out.println(employee1);
        }

    }
    @Test
    public void updateByPrimaryKeyTest(){
        //SqlSession执行映射文件中定义的SQL，并返回映射结果
        Employee employee = new Employee();
        employee.setSid(1);
        employee.setSname("张三");
        employee.setSage(20);
        employee.setSposition("员工");
        List<Employee> list = sqlSession.selectList("com.itheima.mapper.EmployeeMapper.updateByPrimaryKey",employee);
        for (Employee employee1 : list) {
            System.out.println(employee1);
        }

    }



    @After
    public void destory(){
        //提交事务
        sqlSession.commit();
        //关闭事务
        sqlSession.close();
    }
}
